package com.mamingchao.concurrent.cas;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by mamingchao on 2020/7/8.
 */
public class FairReentrantLockTest {
    static ReentrantLock lock = new ReentrantLock(true);

    public static class Patient implements Runnable{

        private String name;

        Patient(String name){this.name = name;}

        /**
         * When an object implementing interface <code>Runnable</code> is used
         * to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p>
         * The general contract of the method <code>run</code> is that it may
         * take any action whatsoever.
         *
         * @see Thread#run()
         */
        @Override
        public void run() {
            for (int i=0;i< 10;i++) {
                try {
                    lock.lock();
                    TimeUnit.MILLISECONDS.sleep(new Random().nextInt(1000));
                    System.out.printf("Thread %s has come in ", name);
                    System.out.println();

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    lock.unlock();
                }
            }
        }


    }

    public static void main(String[] args) {
        for (int i=0;i<2;i++) {
            new Thread(new Patient("patient - " + i)).start();
        }
    }
}
